<?php
	require_once 'init.php';
	
	if ( $_SERVER["REQUEST_METHOD"] == "POST" )
	{
        $username = $util->quotes($_POST["username"]);
        $company = $util->quotes($_POST["company"]);
		$address = $util->quotes($_POST["address"]);
		$telephone = $util->quotes($_POST["telephone"]);        
        $mobilephone = $util->quotes($_POST["mobilephone"]);
        $position = $util->quotes($_POST["position"]);        
        $email = $util->quotes($_POST["email"]);
		
		$clientname = $util->quotes($_POST["clientname"]);
		$clientaddress = $util->quotes($_POST["clientaddress"]);
		$clientphone = $util->quotes($_POST["clientphone"]);
        $clientemail = $util->quotes($_POST["clientemail"]);
        $clientmemo = $util->quotes($_POST["clientmemo"]);
		
        $usernc = $_SESSION['unc'];		
		$useraction = false;
		$orderaction= false;
		$errors = array();
		$message = array();
		$returl_url="";
		
		if ($username != "" && $company != "" && $mobilephone != "" && $position != "" && $email != "") 
		{       
			if($util->check_email_regex($email))
			{
				if($util->check_phone_regex($mobilephone))
				{
					if($telephone == ""||$util->check_tel_regex($telephone))
					{
						if(!empty($_SESSION['idStr'])&&!empty($_SESSION['numStr']))
						{
							$useraction = true;
						}
					}
					else
					{
						array_push($errors,"采购人单位电话");						
					}
				}
				else
				{
					array_push($errors,"采购人手机号码");					
				}
			}
			else
			{
				array_push($errors,"采购人电子邮件");
			}
		}
		else
		{
			array_push($errors,"采购人信息");
		}
		
		if ($clientname != "" && $clientaddress != "" && $clientphone != "") 
		{       
			if($clientemail==""||$util->check_email_regex($clientemail))
			{
				if($util->check_phone_regex($clientphone))
				{
				    if(!empty($_SESSION['idStr'])&&!empty($_SESSION['numStr']))
					{
						$orderaction=true;
					}
				}
				else
				{
					array_push($errors,"收货人手机号码");
				}
			}
			else
			{
				array_push($errors,"收货人电子邮件");
			}
		}
		else
		{
			array_push($errors,"收货人信息");
		}	
		
		if(!empty($errors))
		{
			echo "<script>alert('请正确填写".implode(",",$errors)."');window.location.href='confirm.php';</script>";
			exit;
		}
		
		if($useraction)
		{
			//Check Login, if Login Update, else Insert 
			if($usernc!="")
			{
				//Query current user
				$user = $adminDB->executeSQL("select u.id,u.fdLogin,u.fdName from ".$util->userdbName().".tbUser u where u.fdLogin='".trim($usernc)."'",$connID);								
			}
			else
			{
				$user = $adminDB->executeSQL("select u.id,u.fdLogin,u.fdName from ".$util->userdbName().".tbUser u where u.fdLogin='".trim($email)."'", $connID);
				//Query User Name
				if (empty($user)) 
				{	
					//Try Insert User
					if (!$adminDB->executeSQL("insert into ".$util->userdbName().".tbUser(fdLogin, fdName, fdCompany, fdPosition, fdPassword) values('".trim($email)."', '".trim($username)."', '".trim($company)."', '".trim($position)."', md5('".substr($mobilephone,-6)."'))", $connID)) 
					{			
						echo "<script>alert('用户添加失败！');window.location.href='confirm.php';</script>";
						exit;
					} 
					else 
					{
						//Select New User
						$userid = mysql_insert_id();								
						//Check and Insert Address Text
						if (!$adminDB->executeSQL("insert into ".$util->userdbName().".tbAddress(fdUserID, fdAddress, fdDefault) values('".$userid."', '".trim($address)."', 0)", $connID))
						{
							
						}
						
						//Check and Insert Telephone Text [Type=0]
						if ($adminDB->executeSQL("insert into ".$util->userdbName().".tbPhone(fdUserID, fdPhone, fdDefault, fdTypeID) values('".$userid."', '".trim($telephone)."', 0,0)", $connID))
						{
							
						}
						
						//Check and Insert Mobilephone Text [Type=1]
						if ($adminDB->executeSQL("insert into ".$util->userdbName().".tbPhone(fdUserID, fdPhone, fdDefault, fdTypeID) values('".$userid."', '".trim($mobilephone)."', 0,1)", $connID))
						{
							
						}
						
						//Check and Insert Email Text
						if ($adminDB->executeSQL("insert into ".$util->userdbName().".tbEmail(fdUserID, fdEmail, fdDefault) values('".$userid."', '".trim($email)."', 0)", $connID))
						{
							
						}
						
						$user = $adminDB->executeSQL("select id,fdLogin, fdName from ".$util->userdbName().".tbUser where id='".$userid."'",$connID);
						
						if (isset($_SESSION["unc"])) {
							session_unregister('unc');
						}
						$_SESSION['unc'] = $email;
						if (isset($_SESSION["un"])) {
							session_unregister('un');
						}
						$_SESSION['un'] = $username;

						array_push($message,"自动注册会员成功，帐号为采购邮箱，初始密码为手机号后6位。");
					}
				}
				else
				{
					if (isset($_SESSION["unc"])) {
						session_unregister('unc');
					}
					$_SESSION['unc'] = $user[0]['fdLogin'];
					if (isset($_SESSION["un"])) {
						session_unregister('un');
					}
					$_SESSION['un'] = $user[0]['fdName'];
				}
			}
		}
				
	
		if($orderaction)			
		{
			//Try Insert Order
			if($adminDB->executeSQL("insert into ".$util->contentdbName().".tbOrder(fdOperatorID,fdUserID,fdUserPhone,fdClient, fdClientPhone, fdClientAddress, fdEmail, fdMemo, fdCreate,fdStatus,fdUserCompany,fdUserAddress,fdUserName,fdUserTelephone,fdUserPosition,fdUserEmail) values(0,".$user[0]['id'].", '".trim($mobilephone)."','".trim($clientname)."','".trim($clientphone)."', '".trim($clientaddress)."', '".trim($clientemail)."','".trim($clientmemo)."',now(),0,'".trim($company)."','".trim($address)."', '".trim($username)."', '".trim($telephone)."','".trim($position)."','".trim($email)."')", $connID))
			{
				//load orderid after insert
				$orderid = mysql_insert_id();
				$syncid = substr(strval($orderid+100000),1,5);
				if($_POST["btnsubmit"]=="confirm")
				{
					$adminDB->executeSQL("update ".$util->contentdbName().".tbOrder set fdSubmit=now(), fdStatus = 1, fdSyncID = '".date("Ymd").$syncid."' where id=".$orderid."", $connID);
				}
			
			   //query product info
				$arrayIds = explode('@', $_SESSION['idStr']);
				$arrayNums = explode('@', $_SESSION['numStr']);
				$arrayCarInfos = array();
				$totalPrice = 0;
				for ($i = 0; $i < count($arrayIds); $i ++) {
					$productid = $arrayIds[$i];
					//echo "<script>alert('".$productid."');</script>";
					if ($productid != '') {
						$productinfo = $adminDB->executeSQL("select id, fdName,fdLicense,fdPrice,fdVersion from ".$util->contentdbName().".tbProduct where id = ".$productid."", $connID);						
						
						if($_POST["btnsubmit"]=="confirm"){
						$adminDB->executeSQL("insert into ".$util->contentdbName().".tbItem(fdOrderID,fdProductID,fdDate,fdPrice,fdCount,fdSyncID,fdStatus)values(".$orderid.", ".$productid.", now(), ".$productinfo[0]['fdPrice'].",".$arrayNums[$i].",'sync',1)", $connID);
						}
						else{
						$adminDB->executeSQL("insert into ".$util->contentdbName().".tbItem(fdOrderID,fdProductID,fdDate,fdPrice,fdCount,fdSyncID,fdStatus)values(".$orderid.", ".$productid.", now(), ".$productinfo[0]['fdPrice'].",".$arrayNums[$i].",'sync',0)", $connID);
						}			            
					}
				}
				
				//Clear Cart
				$cart = new Cart($_SESSION['idStr'], $_SESSION['numStr']);
				$cart->setCartNull();
				$_SESSION['idStr'] = $cart->getIdStr();
				$_SESSION['numStr'] = $cart->getNumStr();
				
				array_push($message,"订单提交成功，销售代表将会联系您。");
				$returl_url = "userorder.php";
			}
			else
			{
				array_push($message,"订单提交失败！");
				$returl_url = "confirm.php";
			}
			
			echo "<script>alert('".implode(",",$message)."');window.location.href='".$returl_url."';</script>";
		}	
	}
?>